package com.xzuf.nc;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.swing.DefaultCellEditor;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;

import org.apache.commons.lang.StringUtils;
import org.dom4j.DocumentException;
import org.jdesktop.swingx.JXTable;

import com.xzuf.pub.GlobalValue;
import com.xzuf.pub.exception.CommonException;

/**
 * 方案设置对话框
 * @author xzgf
 * @since 2008-9-26
 * @version 1.0
 */
public class CntrastFieldDialog extends JDialog implements ActionListener{
	
	private JButton btn_load = new JButton("加载");
	private JButton btn_selectFile = new JButton("选择模板文件");
	private JButton btn_loadScheme = new JButton("加载方案");
	private JButton btn_saveScheme = new JButton("保存方案");
	private String docType;
	private static String xmlFilePath;
	private JTextField tf_XmlFilePath;
	private JTextField tf_XmlSchemePath;
	private String sql;
	
	private JXTable headTable = new JXTable();
	private JXTable bodyTable = new JXTable();
	
	private List<List<TempletSchemeVO>> currentScheme = null;

	public CntrastFieldDialog(Frame parent,String docType,String strSql) {
		super(parent);
		this.docType = docType;
		this.sql = strSql;
		initialize();
	}
	
	private void initialize() {
		setSize(new Dimension(600,400));
		setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		setLocationRelativeTo(null);
		setModal(true);
		setTitle("导入方案设置");
		
		JPanel btnPanel = new JPanel();
		btnPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
		btn_load.addActionListener(this);
		btn_selectFile.addActionListener(this);
		btn_saveScheme.addActionListener(this);
		btn_loadScheme.addActionListener(this);
		btnPanel.add(btn_load);
		btnPanel.add(btn_selectFile);
		btnPanel.add(btn_saveScheme);
		btnPanel.add(btn_loadScheme);
		
		tf_XmlFilePath = new JTextField(30);
		tf_XmlFilePath.setEditable(false);
		tf_XmlSchemePath = new JTextField(30);
		tf_XmlSchemePath.setEditable(false);

		JPanel pathPanel = new JPanel();
		pathPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
		JLabel lb_FilePath = new JLabel("XML模板文件路径");
		JLabel lb_XmlScheme = new JLabel("方案路径");
		pathPanel.add(lb_FilePath);
		pathPanel.add(tf_XmlFilePath);
		pathPanel.add(lb_XmlScheme);
		pathPanel.add(tf_XmlSchemePath);
		
		add(pathPanel,BorderLayout.NORTH);
		add(getMainPanel(),BorderLayout.CENTER);
		add(btnPanel,BorderLayout.SOUTH);
	}
	
	private JPanel getMainPanel() {
		JPanel mainPanel = new JPanel();
		mainPanel.setLayout(new BorderLayout());
		
		MyTableModel model = new MyTableModel();
		headTable.setModel(model);
		headTable.setDefaultEditor(JComboBox.class,new DefaultCellEditor(getComBoxModel()));
		
		MyTableModel model2 = new MyTableModel();
		bodyTable.setModel(model2);
		bodyTable.setDefaultEditor(JComboBox.class,new DefaultCellEditor(getComBoxModel()));
		
		JTabbedPane tabbPane = new JTabbedPane();
		tabbPane.addTab("主表", new JScrollPane(headTable));
		tabbPane.addTab("子表", new JScrollPane(bodyTable));
		mainPanel.add(tabbPane);
		return mainPanel;
	}
	
	private JComboBox getComBoxModel() {
		String sql = this.sql;
		List<String> list = BDImportTools.parseSqlField(sql);
		DefaultComboBoxModel model = new DefaultComboBoxModel();
		if(list != null && list.size() > 0) {
			Iterator<String> iter = list.iterator();
			model.addElement("");
			while(iter.hasNext()) {
				model.addElement(iter.next());
			}
		}
		JComboBox box = new JComboBox();
		box.setModel(model);
		return box;
	}
	
	private void refreshData(String filePath) {
		List<List<PareValueVO>> tempList = null;
		try {
			tempList = BDImportTools.parseStanderXmlTemplet(filePath, docType);
		} catch (CommonException e) {
			JOptionPane.showMessageDialog(GlobalValue.mainFrame, e.getMessage());
		} catch (DocumentException e) {
			JOptionPane.showMessageDialog(GlobalValue.mainFrame, e.getMessage());
		}
		
		if(tempList == null) {
			JOptionPane.showMessageDialog(GlobalValue.mainFrame, "模板不匹配...");
			return;
		}
		List<PareValueVO> list = tempList.get(0);
		Iterator<PareValueVO> iter = list.iterator();
		MyTableModel model = (MyTableModel)headTable.getModel();
		TempletSchemeVO vo = null;
		PareValueVO vo2 = null;
		model.clearBodyData();
		while(iter.hasNext()) {
			vo = new TempletSchemeVO();
			vo2 = iter.next();
			vo.setXmlTag(vo2.getKey());
			model.addRow(vo);
		}
		
		
		List<PareValueVO> list2 = tempList.get(1);
		if(list2 == null || list2.size() < 0) {
			return;
		}
		Iterator<PareValueVO> iter2 = list2.iterator();
		MyTableModel model2 = (MyTableModel)bodyTable.getModel();
		TempletSchemeVO vo4 = null;
		PareValueVO vo3 = null;
		model2.clearBodyData();
		while(iter2.hasNext()) {
			vo4 = new TempletSchemeVO();
			vo3 = iter2.next();
			vo4.setXmlTag(vo3.getKey());
			model2.addRow(vo4);
		}
	}
	
	private void onSelectFile() {
		JFileChooser fileChooser = new JFileChooser(System.getProperty("c:/"));
		ExampleFileFilter filter = new ExampleFileFilter();
		filter.addExtension("xml");
		filter.setDescription("XML模板文件");
		
		fileChooser.setFileFilter(filter);
		int flag = fileChooser.showOpenDialog(this);
		if(flag != JFileChooser.APPROVE_OPTION) {
			return;
		}
		File file = fileChooser.getSelectedFile();
		String fileName = file.getAbsolutePath();
		if (fileName.indexOf(".") == -1 && (!new File(fileName + ".xls").exists())) {
			fileName += ".xls";
		}
		
		if(file == null) {
			return;
		}
		xmlFilePath = file.getAbsolutePath();
		tf_XmlFilePath.setText(file.getAbsolutePath());
		JOptionPane.showMessageDialog(GlobalValue.mainFrame, "选择文件成功:[" + xmlFilePath + "]");
	}
	
	private void onSaveScheme() {
		try {
			String strFileName =JOptionPane.showInputDialog(GlobalValue.mainFrame, "请输入方案名");
			
			MyTableModel model = (MyTableModel)headTable.getModel();
			MyTableModel model2 = (MyTableModel)bodyTable.getModel();
			List<TempletSchemeVO> list = new ArrayList<TempletSchemeVO>();
			TempletSchemeVO vo = null;
			for(int i=0;i<model.getRowCount();i++) {
				vo = new TempletSchemeVO();
				vo.setXmlTag(String.valueOf(model.getValueAt(i, 0)));
				vo.setValueField(String.valueOf(model.getValueAt(i, 1)));
				vo.setDefaultValue(String.valueOf(model.getValueAt(i, 2)));
				list.add(vo);
			}
			//
			List<TempletSchemeVO> list2 = new ArrayList<TempletSchemeVO>();
			for(int i=0;i<model2.getRowCount();i++) {
				vo = new TempletSchemeVO();
				vo.setXmlTag(String.valueOf(model2.getValueAt(i, 0)));
				vo.setValueField(String.valueOf(model2.getValueAt(i, 1)));
				vo.setDefaultValue(String.valueOf(model2.getValueAt(i, 2)));
				list2.add(vo);
			}
			BDImportTools.saveTempletScheme(list,list2,strFileName);
			
			JOptionPane.showMessageDialog(GlobalValue.mainFrame,"保存成功!!");
		} catch (CommonException e) {
			JOptionPane.showMessageDialog(GlobalValue.mainFrame, e.getMessage());
		} catch (IOException e) {
			JOptionPane.showMessageDialog(GlobalValue.mainFrame, e.getMessage());
		}
	}
	
	private void onLoadScheme() {
		SchemeSelectionDialog dialog = new SchemeSelectionDialog(GlobalValue.mainFrame);
		dialog.setVisible(true);
		PareValueVO vo = dialog.getSelectedVO();
		try {
			if(vo == null) {
				return;
			}
			List<List<TempletSchemeVO>> templetVOAlls = BDImportTools.loadTempletSchemeVOFromFile(vo);
			if(templetVOAlls != null && templetVOAlls.size() >= 1) {
				List<TempletSchemeVO> templetVOs = templetVOAlls.get(0);
				if(templetVOs != null && templetVOs.size() > 0) {
					MyTableModel model = (MyTableModel)headTable.getModel();
					model.clearBodyData();
					Iterator<TempletSchemeVO> iter = templetVOs.iterator();
					while(iter.hasNext()) {
						model.addRow(iter.next());
					}
				}
			}
			
			
			if(templetVOAlls != null && templetVOAlls.size() == 2) {
				List<TempletSchemeVO> templetVOs2 = templetVOAlls.get(1);
				if(templetVOs2 != null && templetVOs2.size() > 0) {
					MyTableModel model = (MyTableModel)bodyTable.getModel();
					model.clearBodyData();
					Iterator<TempletSchemeVO> iter = templetVOs2.iterator();
					while(iter.hasNext()) {
						model.addRow(iter.next());
					}
				}
			}
			//���õ�ǰ�ķ���������
			currentScheme = templetVOAlls;
			tf_XmlSchemePath.setText(String.valueOf(vo.getValue()));
		} catch (CommonException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public List<List<TempletSchemeVO>> getCurrentScheme() {
		return currentScheme;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource() == btn_load) {
			if(tf_XmlFilePath.getText() != null && StringUtils.isNotEmpty(tf_XmlFilePath.getText())) {
				refreshData(tf_XmlFilePath.getText());
			}
			
		}
		if(e.getSource() == btn_selectFile) {
			onSelectFile();
		}
		if(e.getSource() == btn_saveScheme) {
			onSaveScheme();
		}
		if(e.getSource() == btn_loadScheme) {
			onLoadScheme();
		}
	}
}
